<template>
  <div class="contrast-box growth">
    <div class="contrast">
      <div class="c-main-box-box">
        <div class="c-main-box">
          <div class="c-main">
            <div class="c-left">
              <div class="filter-box">
                <div class="title-date">
                  <h3 class="title"><em></em>各{{levelByte.lower}}园所<span>身体发育</span>横向对比</h3>
                  <ul>
                    <li class="btn1" @click="timeSlot(7, 211)">最近7天</li>
                    <li class="btn1" @click="timeSlot(30, 211)">最近30天</li>
                    <li>
                      <date-picker @getData="getData(arguments, 211)"></date-picker>
                    </li>
                  </ul>
                </div>
                <div class="float">
                  <h3>性别选择（单选）</h3>
                  <el-radio :tabList="sex" @getRadio="getRadio(arguments, 211.1)"></el-radio>
                </div>
                <div class="float">
                  <h3>年级选择（单选）</h3>
                  <el-radio :tabList="grade" @getRadio="getRadio(arguments, 211.2)"></el-radio>
                </div>
              </div>
              <div class="echarts-box">
                <div>
                  <h3 class="pointTitle iconfont">平均身高</h3>
                  <bar
                    :settings="averageHeight"
                    v-if="summary.c !== '暂无总结'"
                  ></bar>
                  <no-data v-else :item="'平均身高'" />
                </div>
                <div>
                  <h3 class="pointTitle iconfont">平均体重</h3>
                  <bar
                    :settings="averageWeight"
                    v-if="summary.c !== '暂无总结'"
                  ></bar>
                  <no-data v-else :item="'平均体重'" />
                </div>
              </div>
              <el-summary :data="summary.c"></el-summary>
            </div>
            <div class="c-right">
              <div class="filter-box">
                <div class="title-date">
                  <h3 class="title"><em></em>各{{levelByte.lower}}儿童<span>身体发育</span>纵向对比</h3>
                  <ul>
                    <li class="btn1 on" @click="timeSlot(90, 212)">最近3个月</li>
                    <li>
                      <month-range @getMonthRange="getMonthRange(arguments, 212)"></month-range>
                    </li>
                  </ul>
                </div>
                <div style="margin-bottom: 20px">
                  <h3>【{{areaName}}】选择{{levelByte.lower}}（多选）</h3>
                  <el-checkbox :tabList="cityList" @getCheckBox="getCheckBox(arguments, 212)"></el-checkbox>
                </div>
                <div class="float">
                  <h3>性别选择（单选）</h3>
                  <el-radio :tabList="sex" @getRadio="getRadio(arguments, 212.1)"></el-radio>
                </div>
                <div class="float">
                  <h3>年级选择（单选）</h3>
                  <el-radio :tabList="grade" @getRadio="getRadio(arguments, 212.2)"></el-radio>
                </div>
              </div>
              <div class="echarts-box">
                <pie-pie :dataList="dataList"></pie-pie>
              </div>
              <el-summary v-show="false" :data="summary.l"></el-summary>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import ElCheckbox from '@/common/elementUi/ElCheckbox'
import DatePicker from '@/common/elementUi/EldatePicker'
import ElRadio from '@/common/elementUi/ElRadio'
import ElLine from '@/common/echarts/Line'
import MonthRange from '@/common/layerUi/MonthRange'
import Bar from '@/common/echarts/Bar'
import PiePie from './components/PiePie'
import {timeSlot} from '@/common/customTime/customTime'
import ElSummary from '@/common/summary/Summary'
export default {
  name: 'HealthyContrast',
  components: {
    ElCheckbox,
    DatePicker,
    ElRadio,
    ElLine,
    MonthRange,
    Bar,
    PiePie,
    ElSummary
  },
  data () {
    return {
      // 首次登陆
      isOnce: true,
      // 身体发育横向对比
      growthC: {
        time: {
          startTime: '2018-07-29',
          endTime: '2018-07-30'
        },
        sex: '男童',
        grade: '托班',
        data: []
      },
      // 身体发育横向对比
      growthL: {
        time: {
          startTime: '2018-07-29',
          endTime: '2018-07-30'
        },
        cityList: [],
        sex: '男童',
        grade: '托班',
        data: []
      },
      sex: ['男童', '女童'],
      grade: ['托班', '小班', '中班', '大班'],
      summary: {
        c: '...',
        l: '...'
      },
      // 平均身高
      averageHeight: {
        xData: ['白河县', '白河县', '白河县', '白河县', '白河县', '白河县', '白河县', '白河县'],
        data: [137, 145, 134, 124, 136, 135, 143, 147],
        linearGradient: ['#33b3b7', '#53e9ee'],
        yName: '身高（cm）',
        labelHide: true,
        labelNuit: '{c}',
        grid: {
          top: '18%',
          left: '0%',
          right: '0%',
          bottom: '0%',
          containLabel: true
        }
      },
      // 平均体重
      averageWeight: {
        xData: ['白河县', '白河县', '白河县', '白河县', '白河县', '白河县', '白河县', '白河县'],
        data: [20, 24, 25, 26, 28, 23, 22, 21],
        linearGradient: ['#d0bb66', '#ffe98f'],
        yName: '体重（kg）',
        labelHide: true,
        labelNuit: '{c}',
        grid: {
          top: '18%',
          left: '0%',
          right: '0%',
          bottom: '0%',
          containLabel: true
        }
      },
      // 身体发育纵向对比
      dataList: [
        {
          title: '榆林市',
          data:
          [
            {
              title: '2018-06月',
              data: [
                {value: 0, name: '偏轻'},
                {value: 0, name: '均值'},
                {value: 0, name: '肥胖'},
                {value: 0, name: '偏重'},
                {value: 0, name: '超重'}
              ]
            },
            {
              title: '2018-07月',
              data: [
                {value: 0, name: '偏轻'},
                {value: 0, name: '均值'},
                {value: 0, name: '肥胖'},
                {value: 0, name: '偏重'},
                {value: 0, name: '超重'}
              ]
            },
            {
              title: '2018-08月',
              data: [
                {value: 0, name: '偏轻'},
                {value: 0, name: '均值'},
                {value: 0, name: '肥胖'},
                {value: 0, name: '偏重'},
                {value: 0, name: '超重'}
              ]
            }
          ]
        },
        {
          title: '商洛市',
          data:
          [
            {
              title: '2018-06月',
              data: [
                {value: 0, name: '偏轻'},
                {value: 0, name: '均值'},
                {value: 0, name: '肥胖'},
                {value: 0, name: '偏重'},
                {value: 0, name: '超重'}
              ]
            },
            {
              title: '2018-07月',
              data: [
                {value: 0, name: '偏轻'},
                {value: 0, name: '均值'},
                {value: 0, name: '肥胖'},
                {value: 0, name: '偏重'},
                {value: 0, name: '超重'}
              ]
            },
            {
              title: '2018-08月',
              data: [
                {value: 0, name: '偏轻'},
                {value: 0, name: '均值'},
                {value: 0, name: '肥胖'},
                {value: 0, name: '偏重'},
                {value: 0, name: '超重'}
              ]
            }
          ]
        }
      ]
    }
  },
  computed: {
    levelByte () {
      let obj = {
        curr: '省',
        lower: '市'
      }
      switch (this.areaLevel) {
        case '省级':
          obj = {
            curr: '省',
            lower: '市'
          }
          break
        case '市级':
          obj = {
            curr: '市',
            lower: '区'
          }
          break
        case '区级':
          obj = {
            curr: '区',
            lower: '园'
          }
          break
      }
      return obj
    },
    ...mapGetters({
      // 当前区域名称
      areaName: 'area',
      // 区域等级
      areaLevel: 'areaLevel',
      // 选择对比项
      cityList: 'areaMapList'
    })
  },
  async mounted () {
    // 初始化所有边框样式
    this.$common.border(window.$('.contrast'))
    await this.$store.dispatch('fetchAreaIdList')
    await this.$store.dispatch('fetchMapFeatures')

    this.growthL.cityList = this.cityList.slice(0, 3)

    this.timeSlot(7, 211)
    this.timeSlot(90, 212)
    window.$('.title-date li').click(function () {
      window.$(this).closest('li').addClass('on').siblings().removeClass('on')
    })
  },
  watch: {
    // 出勤情况横向对比
    'growthC.time': {
      deep: true,
      handler: function () {
        this.getGrowthC()
      }
    },
    'growthC.sex': {
      deep: true,
      handler: function () {
        this.dayGrowthC()
      }
    },
    'growthC.grade': {
      deep: true,
      handler: function () {
        this.dayGrowthC()
      }
    },
    'growthL.time': {
      deep: true,
      handler: function () {
        this.getGrowthL()
      }
    },
    'growthL.cityList': {
      deep: true,
      handler: function () {
        this.getGrowthL()
      }
    },
    'growthL.sex': {
      deep: true,
      handler: function () {
        this.getGrowthL()
      }
    },
    'growthL.grade': {
      deep: true,
      handler: function () {
        this.getGrowthL()
      }
    }
  },
  methods: {
    getGrowthC () {
      let data = {}
      const StartDate = this.growthC.time.startTime + ' 00:00:01'
      const EndDate = this.growthC.time.endTime + ' 23:59:59'
      const idObj = this.getAreaId(this.areaName)
      switch (this.areaLevel) {
        case '省级':
          data = {ProvinceId: idObj[0].ProvinceId, CityId: 0, DistrictId: 0, Gid: 0, IsMonth: false, StartDate: StartDate, EndDate: EndDate}
          break
        case '市级':
          data = {ProvinceId: idObj[0].ProvinceId, CityId: idObj[0].CityId, DistrictId: 0, Gid: 0, IsMonth: false, StartDate: StartDate, EndDate: EndDate}
          break
        case '区级':
          data = {ProvinceId: idObj[0].ProvinceId, CityId: idObj[0].CityId, DistrictId: idObj[0].DistrictId, Gid: 0, IsMonth: false, StartDate: StartDate, EndDate: EndDate}
          break
      }
      window.$.ajax({
        url: 'http://api.youjiaoyun.net/weixin.asmx/GetAvgBodyCheckResult?jsoncallback=?',
        dataType: 'jsonp',
        data: data,
        jsonp: 'jsoncallback',
        async: false,
        success: (res) => {
          this.growthC.data = res
          this.dayGrowthC()
        }
      })
    },
    dayGrowthC () {
      const res = this.growthC.data
      let sexv = 0
      let gradev = 1
      switch (this.growthC.sex) {
        case '女童':
          sexv = 0
          break
        case '男童':
          sexv = 1
          break
      }
      switch (this.growthC.grade) {
        case '托班':
          gradev = 1
          break
        case '小班':
          gradev = 2
          break
        case '中班':
          gradev = 3
          break
        case '大班':
          gradev = 4
          break
      }
      const result = res.filter((p) => {
        return p.Gender === sexv && p.GradeNum === gradev
      })
      const arr = {
        name: [],
        value: {
          height: [],
          weight: []
        }
      }
      for (let i = 0, len = this.cityList.length; i < len; i++) {
        const filterData = result.filter((p) => {
          return p.AreaName === this.cityList[i]
        })
        if (filterData[0]) {
          arr.name.push(this.cityList[i])
          arr.value.height.push(filterData[0].AvgHeight)
          arr.value.weight.push(filterData[0].AvgWeight)
        } else {
          arr.name.push(this.cityList[i])
          arr.value.height.push(0)
          arr.value.weight.push(0)
          this.averageHeight.xData = arr.name
        }
      }
      // 平均身高
      this.averageHeight.xData = arr.name
      this.averageHeight.data = arr.value.height
      // 平均体重
      this.averageWeight.xData = arr.name
      this.averageWeight.data = arr.value.weight
      // 总结语
      let summaryArr = {
        height: [],
        weight: []
      }
      for (let i = 0, len = arr.name.length; i < len; i++) {
        summaryArr.height.push({
          name: arr.name[i],
          value: arr.value.height[i]
        })
        summaryArr.weight.push({
          name: arr.name[i],
          value: arr.value.weight[i]
        })
      }
      summaryArr = {
        height: this.$common.compareSort(summaryArr.height, 'value'),
        weight: this.$common.compareSort(summaryArr.weight, 'value')
      }
      let summary = ''
      if (result.length) {
        summary = '在全' + this.levelByte.curr +'范围下，各' + this.levelByte.lower + '在' + this.growthC.time.startTime + '至' + this.growthC.time.endTime + '的对比情况如下：<br>平均身高最高：' + summaryArr['height'][0].name + ' 平均体重最重：' + summaryArr['weight'][0].name + '<br>平均身高最低：' + summaryArr['height'][summaryArr['height'].length - 1].name + ' 平均体重最轻：' + summaryArr['weight'][summaryArr['weight'].length - 1].name // eslint-disable-line
      } else {
        summary = '暂无总结'
      }
      this.summary.c = summary
    },
    getMonthDays (myMonth) {
      let now = new Date()
      let nowYear = now.getYear()
      nowYear += (nowYear < 2000) ? 1900 : 0
      const monthStartDate = new Date(nowYear, myMonth, 1)
      const monthEndDate = new Date(nowYear, myMonth + 1, 1)
      const days = (monthEndDate - monthStartDate) / (1000 * 60 * 60 * 24)
      return days
    },
    // 身体发育纵向对比
    getGrowthL () {
      const cityList = this.growthL.cityList
      this.dataList = []
      for (let i = 0, len = cityList.length; i < len; i++) {
        this.dataList.push({
          title: cityList[i],
          data:
          [
            {
              title: '',
              data: []
            },
            {
              title: '',
              data: []
            },
            {
              title: '',
              data: []
            }
          ]
        })
      }
      const date = new Date()
      let time = date.getMonth()
      // 当月
      let day = this.getMonthDays(time)
      let StartDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-01'
      let EndDate = date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + day
      this.GetGrowthL(StartDate, EndDate, 0)
      // 上月
      day = this.getMonthDays(time - 1)
      StartDate = date.getFullYear() + '-' + (date.getMonth()) + '-01'
      EndDate = date.getFullYear() + '-' + (date.getMonth()) + '-' + day
      this.GetGrowthL(StartDate, EndDate, 1)
      // 上上月
      day = this.getMonthDays(time - 2)
      StartDate = date.getFullYear() + '-' + (date.getMonth() - 1) + '-01'
      EndDate = date.getFullYear() + '-' + (date.getMonth() - 1) + '-' + day
      this.GetGrowthL(StartDate, EndDate, 2)
    },
    GetGrowthL (StartDate, EndDate, idx) {
      const idObj = this.getAreaId(this.areaName)
      let data = {}
      switch (this.areaLevel) {
        case '省级':
          data = {ProvinceId: idObj[0].ProvinceId, CityId: 0, DistrictId: 0, Gid: 0, IsMonth: true, StartDate: StartDate, EndDate: EndDate}
          break
        case '市级':
          data = {ProvinceId: idObj[0].ProvinceId, CityId: idObj[0].CityId, DistrictId: 0, Gid: 0, IsMonth: true, StartDate: StartDate, EndDate: EndDate}
          break
        case '区级':
          data = {ProvinceId: idObj[0].ProvinceId, CityId: idObj[0].CityId, DistrictId: idObj[0].DistrictId, Gid: 0, IsMonth: true, StartDate: StartDate, EndDate: EndDate}
          break
      }
      window.$.ajax({
        url: 'http://api.youjiaoyun.net/weixin.asmx/GetBodyCheckResultList?jsoncallback=?',
        dataType: 'jsonp',
        data: data,
        jsonp: 'jsoncallback',
        async: false,
        success: (res) => {
          this.growthL.data = res
          this.MonthGrowthL(StartDate, idx)
        }
      })
    },
    avgHW (res, sex, areaName) {
      let arr = []
      let BMI = []
      if (this.$store.state.mapArea.level === '省级') {
        BMI = res.filter((item) => {
          return item.Gender === sex
        })
      } else {
        let name = ''
        switch (this.$store.state.mapArea.level) {
          case '省级':
            name = 'CityName'
            break
          case '市级':
            name = 'DistrictName'
            break
          case '区级':
            name = 'GardenName'
            break
        }
        BMI = res.filter((item) => {
          return item.Gender === sex && item[name] === areaName
        })
      }
      BMI = this.$common.compare(BMI, 'BMIResult')
      if (Object.keys(BMI).length !== 0) {
        const defaultVal = {
          '偏轻': 0,
          '均值': 0,
          '肥胖': 0,
          '偏重': 0,
          '超重': 0
        }
        for (let key in defaultVal) {
          BMI[key] ? defaultVal[key] = BMI[key] : defaultVal[key] = 0
        }
        window.$.each(defaultVal, (key, value) => {
          arr.push({
            name: key,
            value: value
          })
        })
      } else {
        arr = [{name: '暂无数据', value: 0}]
      }
      return arr
    },
    MonthGrowthL (StartDate, idx) {
      const res = this.growthL.data
      let sexv = 0
      let gradev = 1
      switch (this.growthL.sex) {
        case '女童':
          sexv = 0
          break
        case '男童':
          sexv = 1
          break
      }
      switch (this.growthL.grade) {
        case '托班':
          gradev = 1
          break
        case '小班':
          gradev = 2
          break
        case '中班':
          gradev = 3
          break
        case '大班':
          gradev = 4
          break
      }
      let name = ''
      switch (this.areaLevel) {
        case '省级':
          name = 'CityName'
          break
        case '市级':
          name = 'DistrictName'
          break
        case '区级':
          name = 'GardenName'
          break
      }
      const result = res.filter((p) => {
        return p.Gender === sexv && p.GradeNum === gradev
      })
      const cityList = this.growthL.cityList
      for (let i = 0, len = cityList.length; i < len; i++) {
        const filter = result.filter((p) => {
          return p[name] === cityList[i]
        })
        const data = this.avgHW(filter, sexv, cityList[i])
        this.dataList[i].title = cityList[i]
        this.dataList[i].data[idx].title = StartDate.split('-')[1] + '月份'
        this.dataList[i].data[idx].data = data
      }
      if (idx === 2) {
        // 总结语
        console.log(this.dataList)
        // let summaryArr = {
        //   height: [],
        //   weight: []
        // }
        // for (let i = 0, len = arr.name.length; i < len; i++) {
        //   summaryArr.height.push({
        //     name: arr.name[i],
        //     value: arr.value.height[i]
        //   })
        //   summaryArr.weight.push({
        //     name: arr.name[i],
        //     value: arr.value.weight[i]
        //   })
        // }
        // summaryArr = {
        //   height: this.$common.compareSort(summaryArr.height, 'value'),
        //   weight: this.$common.compareSort(summaryArr.weight, 'value')
        // }
        // let summary = '在全' + this.levelByte.curr +'范围下，各' + this.levelByte.lower + '在' + this.growthC.time.startTime + '至' + this.growthC.time.endTime + '的对比情况如下：<br>平均身高最高：' + summaryArr['height'][0].name + ' 平均体重最重：' + summaryArr['weight'][0].name + '<br>平均身高最低：' + summaryArr['height'][summaryArr['height'].length - 1].name + ' 平均身高最低：' + summaryArr['weight'][summaryArr['weight'].length - 1].name // eslint-disable-line
        // this.summary.c = summary
      }
    },
    // 获取该地区id
    getAreaId (name) {
      return this.$store.state.areaIdList.filter((item) => {
        return item.ProvinceName === name || item.CityName === name || item.DistrictName === name
      })
    },
    // 最近一段时间
    timeSlot (d, i) {
      const res = timeSlot(d)
      switch (i) {
        case 211:
          this.growthC.time.startTime = res.t1
          this.growthC.time.endTime = res.t2
          break
        case 212:
          this.growthL.time.startTime = res.t1
          this.growthL.time.endTime = res.t2
          break
      }
    },
    // 开始结束时间(天)
    getData (d, i) {
      const res = d[0]
      switch (i) {
        case 211:
          this.growthC.time.startTime = res.t1
          this.growthC.time.endTime = res.t2
          break
      }
    },
    // 城市多选
    getCheckBox (d, i) {
      const res = d[0]
      switch (i) {
        case 212:
          this.growthL.cityList = res
          break
      }
    },
    // 开始结束时间(月)
    getMonthRange (d, i) {
      const res = d[0]
      switch (i) {
        case 212:
          this.growthL.time.startTime = res.t1
          this.growthL.time.endTime = res.t2
          break
      }
    },
    // 城市单选
    getRadio (d, i) {
      const res = d[0]
      switch (i) {
        case 211.1:
          this.growthC.sex = res
          break
        case 211.2:
          this.growthC.grade = res
          break
        case 212.1:
          this.growthL.sex = res
          break
        case 212.2:
          this.growthL.grade = res
          break
      }
    }
  }
}
</script>

<style lang="stylus" scoped>
.echarts-box > div
  display: flex
  flex-direction: column
  height: 50%
  .bar
    flex: 1
</style>
